package com.block.datapush.service.apipush;


import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

import javax.crypto.spec.IvParameterSpec;
import java.util.HashMap;
import java.util.Map;

/**
 * 优闪贷
 */

@Service
public class YouShanDaiPushApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();

        String mobileMd5 = memberSourceInfo.getMobileMd5();

        String city = memberSourceInfo.getCity();

        if (StrUtil.endWith(city, "市")) {
            city = memberSourceInfo.getCity().substring(0, memberSourceInfo.getCity().length() - 1);
        }

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("channelSource", pushApiKeyParam.getApiCode());
        paramMap.put("city", city);
        paramMap.put("phoneNo", mobileMd5);


        log.info("【优闪贷】撞库开始【queryUrl】{}【bizParam】{}", queryUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【优闪贷】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        String code = resultObject.getString("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(String.valueOf(code));
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "0000")) {
            pushApiResult.setPushSuccess(true);
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String requestUrl = pushApiKeyParam.getRegisterUrl();

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("channelSource", pushApiKeyParam.getApiCode());
        paramMap.put("cust_name", memberSourceInfo.getRealname());
        paramMap.put("mobile", memberSourceInfo.getMobile());

        String city = memberSourceInfo.getCity();

        if (StrUtil.endWith(city, "市")) {
            city = memberSourceInfo.getCity().substring(0, memberSourceInfo.getCity().length() - 1);
        }

        paramMap.put("city", city);
        paramMap.put("sex", memberSourceInfo.getSex());
        paramMap.put("age", memberSourceInfo.getAge());
        paramMap.put("apply_limit", getloan(memberSourceInfo.getLoanAmount()));


        String encrypt = null;
        try {
            encrypt = encrypt3DES(JSON.toJSONString(paramMap), pushApiKeyParam.getApiKey(), pushApiKeyParam.getApiSecret());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("data", encrypt);

        log.info("【优闪贷】导单开始【requestUrl】{}【paramMap】{}", requestUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(bizMap))
                .execute().body();
        log.info("【优闪贷】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);

        JSONObject data = resultObject.getJSONObject("data");
        Integer errorNo = data.getInteger("error_no");
        String errorInfo = data.getString("error_info");

        pushApiResult.setCode(errorNo + "");
        pushApiResult.setMessage(errorInfo);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(errorNo), "0")) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
        } else {
            pushApiResult.setPushSuccess(false);
            pushApiResult.setSettleFlag(false);
            pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();

        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }


    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        return null;
    }

    public static Integer getloan(String loan) {
        if (StrUtil.equals(BaseTypeInfoEnum.LoanAmount.la004.getValue(), loan)) {
            return 100000;
        } else if (StrUtil.equals(BaseTypeInfoEnum.LoanAmount.la005.getValue(), loan)) {
            return 200000;
        }
        return 50000;
    }


    public static String encrypt3DES(String data, String key, String iv) throws Exception {
        Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
        SecretKeySpec keySpec = new SecretKeySpec(key.getBytes("UTF-8"), "DESede");
        IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes("UTF-8"));
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
        byte[] encrypted = cipher.doFinal(data.getBytes("UTF-8"));
        return Base64.getEncoder().encodeToString(encrypted);
    }

    public static void main(String[] args) {

        Integer errorNo = 0;
        if (StrUtil.equals(String.valueOf(errorNo), "0")) {
            System.out.println("推送成功");
        } else {
            System.out.println("推送失败");
        }
    }
}
